package com.ruoyi.datastatistics.Agreement;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.basedata.domain.vo.ConcentratorCommand;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;

@Service
public class GuoXinDTUV1 {

    public static byte[] heads = {(byte)0xaa,(byte)0x55};
    public static byte[] MeterReadingAll = {(byte)0x02};//抄所有表
    public static byte[] BoundMeter = {(byte)0x03};//绑定表
    public static byte[] MeterReadingOne = {(byte)0x04};//读某一个表读数
    public static byte[] ValveControl = {(byte)0x05};//读某一个表读数
    public static byte[] FrequencyControl = {(byte)0x15};//更改上报频率
    public static byte[] IpPortControl = {(byte)0xff};//更改上报频率
    public static byte[] MeterReadingAllNew = {(byte)0x12};//抄所有表

    public static void main(String[] args) {
      /*  String temp = "00000202004001";
        Integer length = 20;
        String[] meters = new String[length];
        for(int i=0; i< length; i++){
            meters[i] = (Integer.parseInt(temp)+i)+"";
        }*/

        String temp = "aa55f10002000020582400072310000000000000162600072310000000000000723500072310000000000000782600072310000000000000534000072310000000000000743200072310000000000000504000072310000005000000583000072310000001000000382600072310000000000000312000072310000000000000332400072310000000000000113000072310000000000000303500072310000000000000682600072310000000000000883500072310000000000000863200072310000000000000203600072310000000000000953000072310000000000000823500072310000000000000034000072310000000000000b2";
       // byte[] data = getCommandDataForBoundMeter(meters);
       // String s = "123.60.21.230";
       // String[] t = s.split("\\.");
        //byte[] data = getCommandDataForMeterReadingAllNew();
        String ip = "218.92.234.138";//zhengshi aa 55 06 00 ff 00 00 da 5c ea 8a 12 20 e0
        String port = "8210";//aa 55 06 00 ff 00 00 2f 60 7f 46 48 26 c6
       // String ip = "47.96.127.70";
        //String port = "9400";//aa 55 06 00 ff 00 00 2f 60 7f 46 b8 24 34

       /* byte[] data = getCommandDataForIpPortControl(ip,port);
        System.out.println(convertString(data));*/

        byte[] bit = hexStringToByteArray(temp);
        //System.out.println(getTimeVFromByte(bit));
        System.out.println(GetBufferPacketForAll(bit));
    }
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
    /**
     * 控制命令返回解析
     * @param bit
     * @return
     */
    public static JSONObject GetResult(byte[] bit,Integer commandType){
        JSONObject jo = new JSONObject();
        boolean flag = getCsForAllType(bit, 4, null);
        if(flag){
            if(bit[7]==0x01){
                jo.put("code","1");
                jo.put("msg","成功");
            }else{
                jo.put("code","0");
                jo.put("msg","失败");
            }
        }
        return jo;
    }
    /**
     * 解析日冻结数据
     * @param bit
     * @return
     */
    public static JSONObject GetBufferPacketForAll(byte[] bit)
    {

        JSONObject jo = new JSONObject();
        byte[] type = { 0x02 };
        boolean flag = getCsForAllType(bit, 4, null);
        if (flag)
        {
            try
            {
                jo = getDSDateinfoFromByte(bit);
                //jo = getDSDateinfoFromByte(bit);
            }
            catch (Exception e)
            {
                return null;
            }
            return jo;
        }
        else
        {
            return null;
        }

    }

    /**
     * 解析日冻结数据
     * @param bit
     * @return
     */
    public static JSONObject GetBufferPacketForCommandData(byte[] bit)
    {

        JSONObject jo = new JSONObject();
        byte[] type = { 0x12 };
        boolean flag = getCsForAllType(bit, 4, null);
        if (flag)
        {
            try
            {
                jo = getDSDateinfoFromByte(bit);
                //jo = getDSDateinfoFromByte(bit);
            }
            catch (Exception e)
            {
                return null;
            }
            return jo;
        }
        else
        {
            return null;
        }

    }
    /**
     * 阀控命令-发送
     * @param
     * @param isOpen 1：开，2：关
     * @return
     */
    public static byte[] getCommandDataForValveControl(String concentratorId,String meter,String isOpen){
        if(meter == null || meter.equals("")){
            return null;
        }
        byte[] commandData = new byte[16];
        //头部
        System.arraycopy(heads, 0, commandData, 0, 2);
        //长度
        System.arraycopy(getcommandDataLength(8), 0, commandData, 2, 2);
        //控制码
        System.arraycopy(ValveControl, 0, commandData, 4, 1);
        //表地址
        System.arraycopy(getByte(meter), 0, commandData, 7, 7);
        //阀控
        commandData[commandData.length-2] = (byte)(isOpen.equals("1")? 0 : 1);
        //验证码
        commandData[commandData.length-1] = getTotalForByte(commandData);
        return commandData;
    }
    /**
     * 抄所有表读数
     * @param
     * @return
     */
    public static byte[] getCommandDataForMeterReadingAll(String concentratorAddress){

        byte[] commandData = new byte[8];
        //头部
        System.arraycopy(heads, 0, commandData, 0, 2);
        //长度
        System.arraycopy(getcommandDataLength(0), 0, commandData, 2, 2);
        //控制码
        System.arraycopy(MeterReadingAll, 0, commandData, 4, 1);
        //验证码
        commandData[commandData.length-1] = getTotalForByte(commandData);
        return commandData;
    }
    /**
     * 抄所有表读数 最新
     * @param
     * @return
     */
    public static byte[] getCommandDataForMeterReadingAllNew(){

        byte[] commandData = new byte[8];
        //头部
        System.arraycopy(heads, 0, commandData, 0, 2);
        //长度
        System.arraycopy(getcommandDataLength(0), 0, commandData, 2, 2);
        //控制码
        System.arraycopy(MeterReadingAllNew, 0, commandData, 4, 1);
        //验证码
        commandData[commandData.length-1] = getTotalForByte(commandData);
        return commandData;
    }

    /**
     * 更改上报频率、时间
     * @param
     * @param //0x00 15min ； 0x01 1h ； 0x02 1 天； 0x04 1 月
     * @return
     */
    public static byte[] getCommandDataForFrequencyControl(ConcentratorCommand concentratorCommand){
        if(concentratorCommand == null || StringUtils.isBlank(concentratorCommand.getSendTime())){
            return null;
        }
        String time = concentratorCommand.getSendTime();
        Integer frequency = concentratorCommand.getFrequency() ;
        String concentratorAddress = concentratorCommand.getConcentratorId();
        byte[] commandData = new byte[15];
        //头部
        System.arraycopy(heads, 0, commandData, 0, 2);
        //长度
        System.arraycopy(getcommandDataLength(7), 0, commandData, 2, 2);
        //控制码
        System.arraycopy(FrequencyControl, 0, commandData, 4, 1);
        //时间
        System.arraycopy(getByte2(time), 0, commandData, 7, 6);
        //频率
        commandData[commandData.length-2] = (byte)frequency.intValue();
        //验证码
        commandData[commandData.length-1] = getTotalForByte(commandData);
        return commandData;
    }
    /**
     * 更改IPport
     * @param
     * @param //0x00 15min ； 0x01 1h ； 0x02 1 天； 0x04 1 月
     * @return
     */
    public static byte[] getCommandDataForIpPortControl(String ip,String port,String concentratorAddress){
        if(ip == null || ip.equals("")){
            return null;
        }
        byte[] commandData = new byte[14];
        //头部
        System.arraycopy(heads, 0, commandData, 0, 2);
        //长度
        System.arraycopy(getcommandDataLength(6), 0, commandData, 2, 2);
        //控制码
        System.arraycopy(IpPortControl, 0, commandData, 4, 1);
        //ip
        System.arraycopy(getIp(ip), 0, commandData, 7, 4);
        //port
        System.arraycopy(getport(port), 0, commandData, 11, 2);
        //验证码
        commandData[commandData.length-1] = getTotalForByte(commandData);
        return commandData;
    }
    /***
     * 阀控返回
     * @param bit
     * @return
     */
    public static JSONObject getValveControlReslut(byte[] bit){
        JSONObject jo = new JSONObject();
        byte[] bit_add = new byte[6];
        System.arraycopy(bit, 2, bit_add, 0, 6);
        String temp = getIntFromByte2(bit_add);//终端地址
        jo.put("communicateAddress",temp);
        if(bit[22] == 0x30 &&  bit[24] == 0x02){
            jo.put("status","OK");
        }
        return jo;

    }
    /**
     * 日冻结解析主程序
     * @param bit
     * @return
     */
    public static JSONObject getDSDateinfoFromByte(byte[] bit)
    {
        JSONObject jo = new JSONObject();
        try
        {
            if (bit.length > 8)
            {
                jo.put("type", 4);
                jo.put("type_msg", "直读表国信");//终端类型
                Integer index_num = 8;//01 00 08 23 20 00 00， 00 00 12 00， 01----长度12
                JSONArray json_temp = new JSONArray();
                try{
                    while (index_num < bit.length-1)
                    {
                        JSONObject item = new JSONObject();
                        try{

                            byte[] add = new byte[7];
                            System.arraycopy(bit, index_num, add, 0, add.length);
                            long l = Long.parseLong(getIntFromByteDX(add));
                            item.put("add", String.valueOf(l));
                            //流量
                            byte[] TotalFlow = new byte[4];
                            System.arraycopy(bit, index_num + 7, TotalFlow, 0, TotalFlow.length);
                            if("00102307003987".equals(item.get("add"))){
                                System.out.println(item.get("add"));
                            }
                            item.put("TotalFlow", Double.parseDouble(getIntFromByteXS2(TotalFlow)));
                            //阀控
                            item.put("valveStatus", getValveStatus(bit[index_num + 7 + 4]));
                        }catch (Exception e){

                        }

                        index_num = index_num + 12 ;
                        json_temp.add(item);
                    }
                }catch (Exception e){

                }

                jo.put("info", json_temp);

            }

        }
        catch (Exception e)
        {

        }
        return jo;
    }

    /**
     * 日冻结解析主程序，平台下发命令,添加date时间
     * @param bit
     * @return
     */
    public static JSONObject getDSDateinfoFromByteforCommandData(byte[] bit)
    {
        JSONObject jo = new JSONObject();
        try
        {
            if (bit.length > 8)
            {
                jo.put("type", 4);
                jo.put("type_msg", "直读表国信");//终端类型
                byte[] date = new byte[6];
                System.arraycopy(bit, 7, date, 0, date.length);
                jo.put("date", getIntFromByteDX(date));//终端类型


                Integer index_num = 8 + 6;//01 00 08 23 20 00 00， 00 00 12 00， 01----长度12

                JSONArray json_temp = new JSONArray();

                while (index_num < bit.length-1)
                {
                    JSONObject item = new JSONObject();
                    byte[] add = new byte[7];
                    System.arraycopy(bit, index_num, add, 0, add.length);
                    item.put("add", getIntFromByteDX(add));

                    //流量
                    byte[] TotalFlow = new byte[4];
                    System.arraycopy(bit, index_num + 7, TotalFlow, 0, TotalFlow.length);
                    item.put("TotalFlow", Double.parseDouble(getIntFromByteXS(TotalFlow)));
                    //阀控
                    item.put("valveStatus", getValveStatus(bit[index_num + 7 + 4]));

                    index_num = index_num + 12 ;
                    json_temp.add(item);
                }
                jo.put("info", json_temp);

            }

        }
        catch (Exception e)
        {

        }
        return jo;
    }
    /**
     * 获取绑定表命令
     * @param meters
     * @return
     */
    public static byte[] getCommandDataForBoundMeter(String[] meters,String[] collect,String concentratorAddress){
        if(meters == null || meters.length<0){
            return null;
        }
        byte[] commandData = new byte[8 + 1 + meters.length * 7];
        //头部
        System.arraycopy(heads, 0, commandData, 0, 2);
        //长度
        System.arraycopy(getcommandDataLength(meters.length*7+1), 0, commandData, 2, 2);
        //控制码
        System.arraycopy(BoundMeter, 0, commandData, 4, 1);
        //表个数
        commandData[7] = (byte) Integer.parseInt(meters.length+"",16);
        for(int i =0;i<meters.length;i++){
            System.arraycopy(getByte(meters[i]), 0, commandData, 8+i*7, 7);
        }
        //验证码
        commandData[commandData.length-1] = getTotalForByte(commandData);
        return commandData;
    }

    public static String convertString(byte[] data){
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<data.length; i++){
            String s = Integer.toHexString(data[i] & 0xff);
            s = s.length()<2 ?("0"+s):s;
            sb.append(s);
        }
        return sb.toString();
}
    /**
     * 获取单独抄表命令
     * @param meter
     * @return
     */
    public static byte[] getCommandDataForMeterReadingOne(String meter,String concentratorAddress){
        if(meter == null || meter.equals("")){
            return null;
        }
        byte[] commandData = new byte[15];
        //头部
        System.arraycopy(heads, 0, commandData, 0, 2);
        //长度
        System.arraycopy(getcommandDataLength(7), 0, commandData, 2, 2);
        //控制码
        System.arraycopy(MeterReadingOne, 0, commandData, 4, 1);
        //表地址
        System.arraycopy(getByte(meter), 0, commandData, 7, 7);
        //验证码
        commandData[commandData.length-1] = getTotalForByte(commandData);
        return commandData;
    }
//获取数据包长度
    public static byte[] getcommandDataLength(int length){
        String l_str =  Integer.toHexString(length);
        int l = l_str.length();
        for(int i=0;i<4-l;i++){
            l_str = "0" + l_str;
        }
        byte[] b = new byte[2];
        b[0] =(byte) Integer.parseInt(l_str.substring(2,4),16);
        b[1] =(byte) Integer.parseInt(l_str.substring(0,2),16);
        return b;
    }
    /**
     * 解析 阀控 状态
     * @param bit
     * @return
     */
    public static String getValveStatus(byte bit){
        String flag = "3";
        if((int)bit == 0){
            flag = "1";
        }else {
            flag = "0";
        }
        return flag;
    }

    /**
     * bcd码,示例：109230700049-》0x70 0x30 0x92 0x10 ·······
     * @param ad
     * @return
     */
    public static byte[] getByte(String ad)
    {

        byte[] bit = new byte[7];
        int length = ad.length();
        if(ad.length()<14){
            for(int j=0; j<14-length; j++){
                ad = "0"+ad;
            }
        }
        for (int i = 0; i < 7; i++)
        {
            String temp = ad.substring(i * 2, i * 2+2);
            bit[6-i] = (byte)Integer.parseInt(temp,16);
        }
        return bit;
    }
    /**
     * bcd码,示例：109230700049-》0x10 0x92 0x30 0x70 ·······
     * @param ad
     * @return
     */
    public static byte[] getByte2(String ad)
    {
        int length = ad.length();
        byte[] bit = new byte[length/2];

        for (int i = 0; i < length/2; i++)
        {
            String temp = ad.substring(i * 2, i * 2+2);
            bit[i] = (byte)Integer.parseInt(temp,16);
        }
        return bit;
    }
    /**获取ip
     * 示例：123.15.65.0-》0x7b 0xof 0x41 0x00 ·······
     * @param
     * @return
     */
    public static byte[] getIp(String ip)
    {
        String[] ips = ip.split("\\.");

        byte[] bit = new byte[4];

        for (int i = 0; i < 4; i++)
        {
            bit[i] = (byte)Integer.parseInt(ips[i]);
        }
        return bit;
    }

    /**获取ip
     * 示例：5001-》0x1389 ·······
     * @param
     * @return
     */
    public static byte[] getport(String port)
    {
        Integer iport = Integer.parseInt(port);

        byte[] bit = new byte[2];
        bit[0] =(byte) (iport % 256);
        bit[1] =(byte) (iport / 256);
        return bit;
    }
    /**
     * 验证
     * @param bit
     * @param index
     * @param type
     * @return
     */
    public static boolean getCsForAllType(byte[] bit, int index, byte[] type)
    {
        boolean flag = true;
        if (bit != null & bit.length > 0)
        {
            String l1 = Integer.toHexString(bit[3]& 0xFF);
            String l2 = Integer.toHexString(bit[2] & 0xFF);
            l1 = l1 + (l2.length() < 2 ? ("0" + l2) : l2);
            int  recvlen = Integer.parseInt(l1,16);
            if (type!=null && type.length > 0)
            {
                boolean temp = false;
                for (int i = 0; i < type.length; i++)
                {
                    if (bit[index] == type[i])
                    {
                        temp = true;
                        break;
                    }
                }
                flag = temp;
            }
            if (flag)
            {
                if (bit.length <= 0)
                {
                    flag = false;
                }
                else if (bit[0] != (byte)0xaa)
                {
                    flag = false;
                }
                else if (recvlen != bit.length-8)
                {
                    flag = false;
                }
                else
                {
                    byte[] temp1 = new byte[bit.length - 1];
                    System.arraycopy(bit, 0, temp1, 0, temp1.length);
                    byte temp = getTotalForByte(temp1);
                    if (temp != bit[(bit.length - 1)])
                    {
                        flag = false;
                    }
                }
            }

        }

        return flag;
    }


    /**
     * 验证和
     * @param bit
     * @return
     */
    private static byte getTotalForByte(byte[] bit)
    {
        int sum = 0;
        if (bit.length > 0)
        {
            for (int i = 0; i < bit.length; i++)
            {
                sum = sum + bit[i];
                sum = sum & 0xFF;
            }
        }
        byte rein = (byte)sum;
        return rein;
    }

    /**
     * 两位不足 补零,高位在hou,eg->0x0c 0x02:0c02
     * @param bit
     * @return
     */
    public static String getIntFromByte2(byte[] bit)
    {
        String str = "";
        for (int i = 0; i < bit.length; i++)
        {
            String temp = Integer.toHexString(bit[i]& 0xFF);
            temp = temp.length() < 2 ? ("0" + temp) : temp;
            str = str + temp;
        }
        return str;
    }
    /**
     * 两位不足 补零,高位在hou,eg->0x0c 0x02:020c
     * @param bit
     * @return
     */
    public static String getIntFromByteDX(byte[] bit)
    {
        String str = "";
        for (int i = bit.length-1; i >=0; i--)
        {
            String temp = Integer.toHexString(bit[i]& 0xFF);
            temp = temp.length() < 2 ? ("0" + temp) : temp;
            str = str + temp;
        }
        return str;
    }

    /**
     * 两位不足 补零,高位在hou,eg->0x120x12 0x120x02:121212.02
     * @param bit
     * @return
     */
    public static String getIntFromByteXS(byte[] bit)
    {
        String str = "";
        for (int i = 0; i <bit.length; i++)
        {
            String temp = Integer.toHexString(bit[i]& 0xFF);
            temp = temp.length() < 2 ? ("0" + temp) : temp;
            if(i==bit.length-1){
                str = str +"."+ temp;
            }else{
                str = str + temp;
            }
        }

        return str;
    }
    /**
     * 两位不足 补零,高位在hou,eg->0x120x12 0x120x02:021212.12
     * @param bit
     * @return
     */
    public static String getIntFromByteXS2(byte[] bit)
    {
        String str = "";
        for (int i = bit.length-1; i >-1; i--)
        {
            String temp = Integer.toHexString(bit[i]& 0xFF);
            temp = temp.length() < 2 ? ("0" + temp) : temp;
            if(i == 0){
                str = str +"."+ temp;
            }else{
                str = str + temp;
            }
        }

        return str;
    }
    /**
     * 16进制转10进制
     * @param bytes
     * @return
     */
    public static int getIntFromByte16(byte[] bytes)
    {
        byte[] bit = new byte[4];
        String bit_s = "";
        for (int i= bytes.length -1 ; i>-1; i--)
        {
            bit_s += (Integer.toHexString(bytes[i]& 0xFF).length() == 1 ? "0" + Integer.toHexString(bytes[i]& 0xFF) :Integer.toHexString(bytes[i]& 0xFF));
        }

        int v = 0;
        if (bit.length == 4)
        {
            v = Integer.parseInt(bit_s, 16);

        }
        v = Integer.parseInt(bit_s, 16);
        return v;
    }

    /**
     * 两位不足 补零,eg->0x0c 0x02:1202
     * @param bit
     * @return
     */
    private static String getStringFromByte(byte[] bit)
    {
        String str = "";
        for (int i = 0; i < bit.length; i++)
        {
            String temp = (int)(bit[i]) +"";
            temp = temp.length() < 2 ? ("0" + temp) : temp;
            str = str + temp;
        }
        return str;
    }

    /**
     * 简洁写法 byte数组转成16进制字符串
     * @param bytes byte数组
     * @return 16进制字符串
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(String.format("%02X", b));
        }
        return builder.toString();
    }

}
